package com.acme.cli;

import com.acme.domain.account.Account;
import com.acme.domain.account.CheckingAccount;
import com.acme.domain.account.SavingAccount;
import com.acme.domain.client.Bank;
import com.acme.domain.client.Client;
import com.acme.domain.client.Gender;
import com.acme.exceptions.BankException;
import com.acme.exceptions.NoEnoughFundsException;
import com.acme.service.bank.BankReport;
import com.acme.service.bank.impl.BankService;

import java.io.IOException;
import java.math.BigDecimal;

public class BankApplication {
    private static BankService bankService;
    private static BankReport bankReport;

    public static void main(final String[] args) throws IOException, BankException {
        initServices();
        Bank bank = createInMemoryBank();
        if (args.length > 0 && args[0].equals("-statistics")) {
            printTheBank(bank);
        }
    }

    private static void initServices() {
        bankService = new BankService();
        bankReport = new BankReport();
    }

    private static void printTheBank(final Bank bank) {
        // TODO [MY] Command should be read from console. (see p.5)
        System.out.println(String.format("Total number of clients: %s", bankReport.getNbOfCustomers(bank)));
        System.out.println(String.format("Total number of accounts: %s", bankReport.getNbOfAccounts(bank)));
        System.out.println(String.format("Total credit to clients: %s", bankReport.getBankCredit(bank)));
        System.out.println(String.format("Accounts sorted by balance (descending): %s", bankReport.getAccountsSortedBySum(bank, false)));
    }

    private static Bank createInMemoryBank() throws BankException {
        Bank bank = new Bank();
        Client client1 = bankService.addClient(bank, "John", Gender.MALE);
        Account account1 = new SavingAccount(1, new BigDecimal(100));
        Account account2 = new CheckingAccount(2, new BigDecimal(100), new BigDecimal(150));
        client1.addAccount(account1);
        client1.addAccount(account2);

        Client client2 = bankService.addClient(bank, "Miranda", Gender.FEMALE);
        Account account3 = new SavingAccount(3, new BigDecimal(50));
        Account account4 = new CheckingAccount(4, new BigDecimal(75), new BigDecimal(20));
        client2.addAccount(account3);
        client2.addAccount(account4);

        account1.withdraw(new BigDecimal(30));
        account2.withdraw(new BigDecimal(200));
        account4.withdraw(new BigDecimal(70));

        try {
            account4.withdraw(new BigDecimal(10));
        } catch (NoEnoughFundsException e) {
            e.printStackTrace();
        }

        return bank;
    }
}